<?php
include 'ini.php';

$con = connectToDB();
// TO DO: check if username is taken already
// TO DO: check if email is taken already

$email = $con->real_escape_string($_POST['email']);
$password = $con->real_escape_string($_POST['password']); 
$username = $con->real_escape_string($_POST['username']); 
$confirmPassword = $con->real_escape_string($_POST['confirmPassword']); 


if (empty($password) || empty($confirmPassword) || empty($email) || empty($username))
{
    header("Location: signup.php?err=1"); // TO DO: error upon returning back to register page
    exit();
}

if ( strcmp($password, $confirmPassword) != 0 )
{
    header("Location: signup.php?err=2"); // TO DO: error upon returning back to register page
    exit();
}

if( !ctype_alnum ($username ))
{
    header("Location: signup.php?err=3"); // TO DO: error upon returning back to register page
    exit();
}

if ( !filter_var( $email, FILTER_VALIDATE_EMAIL ) )
{
    header("Location: signup.php?err=4"); // TO DO: error upon returning back to register page
    exit();
}

if ( emailHasBeenTaken($email) )
{
    header("Location: signup.php?err=5"); // TO DO: error upon returning back to register page
    exit();
}

if ( usernameHasBeenTaken($username) )
{
    header("Location: signup.php?err=6"); // TO DO: error upon returning back to register page
    exit();
}



$password = md5( md5($password)); // to do: more secure hashing 

$stmt = $con->prepare("INSERT INTO users(email, username, pass) VALUES(?, ?, ?)");
$stmt->bind_param('sss', $email, $username, $password);
$stmt->execute(); 
$stmt->close();

$userID = $con->insert_id;

setSessionUserID($userID);

header("Location: myaccount.php");